<script setup lang="js">
import { ref,onMounted,computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {updateApplyStatus,getApplyDetail} from "@/api/returnApply.js";
import {fetchComAdList} from "@/api/companyAddress.js";

const defaultUpdateStatusParam = {
  companyAddressId: null,
  handleMan: 'admin',
  handleNote: null,
  receiveMan: 'admin',
  receiveNote: null,
  returnAmount: 0,
  status: 0
};
const defaultOrderReturnApply = {
  id: null,
  orderId: null,
  companyAddressId: null,
  productId: null,
  orderSn: null,
  createTime: null,
  memberUsername: null,
  returnAmount: null,
  returnName: null,
  returnPhone: null,
  status: null,
  handleTime: null,
  productPic: null,
  productName: null,
  productBrand: null,
  productAttr: null,
  productCount: null,
  productPrice: null,
  productRealPrice: null,
  reason: null,
  description: null,
  proofPics: null,
  handleNote: null,
  handleMan: null,
  receiveMan: null,
  receiveTime: null,
  receiveNote: null
};

const orderReturnApply = ref(Object.assign({}, defaultOrderReturnApply))
const updateStatusParam = ref(Object.assign({}, defaultUpdateStatusParam))
const route = useRoute()
const router = useRouter()
const id = ref(null)
const proofPics = ref(null)
const companyAddressList = ref([])
const productList = ref(null)
onMounted(() => {
  getDetail()
})

// TODO: 计算商品总价
const totalAmount = computed(() => {
  if (orderReturnApply.value !=null) {
    return orderReturnApply.value.productRealPrice * orderReturnApply.value.productCount
  } else {
    return 0
  }
})

// TODO: 获取当前地址
function getCurrentAddress() {
  let ids = updateStatusParam.value.companyAddressId;
  if (companyAddressList.value == null) return {};
  for (let i = 0; i < companyAddressList.value.length; i++) {
    let address = companyAddressList.value[i];
    if (address.id === ids) {
      return address;
    }
  }
  return null;
}

// TODO: 格式化订单创建时间
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// TODO: 格式化订单状态
const formatStatus = (status) => {
  if (status === 0) {
    return "待处理";
  } else if (status === 1) {
    return "退货中";
  } else if (status === 2) {
    return "已完成";
  } else {
    return "已拒绝";
  }
}

// TODO: 格式化订单地址
const formatRegion = (address) => {
  let str = address.province;
  if (address.city != null) {
    str += "  " + address.city;
  }
  str += "  " + address.region;
  return str;
}

// TODO: 获取退货订单详情
const getDetail = () => {
  id.value = route.query.id
  getApplyDetail(id.value).then((res) => {
    orderReturnApply.value = res.data.data
    productList.value = []
    productList.value.push(orderReturnApply.value)
    if (orderReturnApply.value.proofPics !=null) {
      proofPics.value = orderReturnApply.value.proofPics.split(",")
    }
    //退货中和完成
    if (orderReturnApply.value.status ===1 || orderReturnApply.value.status === 2) {
      updateStatusParam.value.returnAmount = orderReturnApply.value.returnAmount
      updateStatusParam.value.companyAddressId = orderReturnApply.value.companyAddressId
    }
   getCompanyAddressList();
  })
}

// TODO: 获取退货地址列表
const getCompanyAddressList = () => {
  fetchComAdList().then((res) => {
    companyAddressList.value = res.data.data
    for (let i = 0; i < companyAddressList.value.length; i++) {
      if (companyAddressList.value[i].receiveStatus === 1 && orderReturnApply.value.status === 0) {
        updateStatusParam.value.companyAddressId = companyAddressList.value[i].id;
      }
    }
  })
}

// TODO: 查看订单详情
const handleViewOrder = () => {
  router.push({
    path: '/detail/order',
    query: {
      id: orderReturnApply.value.orderId
    }
  })
}



</script>

<template>
  <div class="apply-detail">
    <div class="apply-card">
      <el-card shadow="never"
               style="border-radius: 5px;margin-bottom: 20px;">
        <span class="font-title">退货商品</span>
        <el-table border
                  class="standard-margin"
                  ref="productTable"
                  :data="productList">
          <el-table-column label="商品图片" align="center">
            <template #default="{row}">
              <img :src="row.productPic" style="height:80px" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center">
            <template #default="{row}">
              <span>名称：{{ row.productName }}</span><br />
              <span>品牌：{{ row.productBrand }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价格/规格" align="center">
            <template #default="{row}">
              <span>价格：￥{{ row.productRealPrice }}</span><br />
              <span>货号：NO.{{ row.productId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品属性" align="center">
            <template #default="{row}">
              {{ row.productAttr }}
            </template>
          </el-table-column>
          <el-table-column label="商品数量" align="center">
            <template #default="{row}">
              {{ row.productCount }}
            </template>
          </el-table-column>
          <el-table-column label="价格小计" align="center">
            <template #default="">
              ￥{{ totalAmount }}
            </template>
          </el-table-column>
        </el-table>
        <div class="total-title">
          <span>合计：</span>
          <span>￥{{totalAmount}}</span>
        </div>
      </el-card>
      <el-card shadow="never">
        <span class="font-title">服务单信息</span>
        <div class="form-container-border">
          <el-row>
            <el-col :span="6" class="form-border form-left-bg font-small">服务单号</el-col>
            <el-col class="form-border font-small" :span="18">{{ orderReturnApply.id }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">申请状态</el-col>
            <el-col class="form-border font-small" :span="18">{{ formatStatus(orderReturnApply.status) }}</el-col>
            </el-row>
          <el-row>
            <el-col :span="6" class="form-border form-left-bg font-small" style="height:50px;line-height:30px">订单编号
            </el-col>
            <el-col class="form-border font-small" :span="18" style="height:50px">
              {{orderReturnApply.orderSn}}
              <el-button type="text" size="small" @click="handleViewOrder">查看</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">申请时间</el-col>
            <el-col class="form-border font-small" :span="18">{{ formatDate(orderReturnApply.createTime) }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">用户账号</el-col>
            <el-col class="form-border font-small" :span="18">{{ orderReturnApply.memberUsername }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">联系人</el-col>
            <el-col class="form-border font-small" :span="18">{{ orderReturnApply.returnName }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">联系电话</el-col>
            <el-col class="form-border font-small" :span="18">{{ orderReturnApply.returnPhone }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">退货原因</el-col>
            <el-col class="form-border font-small" :span="18">{{ orderReturnApply.reason }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">问题描述</el-col>
            <el-col class="form-border font-small" :span="18">{{ orderReturnApply.description }}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">凭证图片</el-col>
            <el-col class="form-border font-small" :span="18" style="height:100px">
              <img v-for="item in proofPics" style="width:80px;height:80px" :src="item" alt="" />
            </el-col>
          </el-row>
        </div>
        <div class="form-container-border">
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">订单金额</el-col>
            <el-col class="form-border font-small" :span="18">￥{{totalAmount}}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">确认退款金额
            </el-col>
            <el-col class="form-border font-small" style="height:52px" :span="18">
              ￥
              <el-input size="small" v-model="updateStatusParam.returnAmount"
                        :disabled="orderReturnApply.status!==0"
                        style="width:200px;margin-left: 10px"></el-input>
            </el-col>
          </el-row>
          <div v-show="orderReturnApply.status!==3">
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">选择收货点
              </el-col>
              <el-col class="form-border font-small" style="height:52px" :span="18">
                <el-select size="small"
                           style="width:200px"
                           :disabled="orderReturnApply.status!==0"
                           v-model="updateStatusParam.companyAddressId">
                  <el-option v-for="address in companyAddressList"
                             :key="address.id"
                             :value="address.id"
                             :label="address.addressName">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">收货人姓名</el-col>
              <el-col class="form-border font-small" :span="18">{{ getCurrentAddress()?.name }}</el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">所在区域</el-col>
              <el-col class="form-border font-small" :span="18">{{ getCurrentAddress()? formatRegion(getCurrentAddress()) : "" }}</el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">详细地址</el-col>
              <el-col class="form-border font-small" :span="18">{{ getCurrentAddress()?.detailAddress }}</el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">联系电话</el-col>
              <el-col class="form-border font-small" :span="18">{{ getCurrentAddress()?.phone }}</el-col>
            </el-row>
          </div>
        </div>
        <div class="form-container-border" v-show="orderReturnApply.status!==0">
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">处理人员</el-col>
            <el-col class="form-border font-small" :span="18">{{orderReturnApply.handleMan}}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">处理时间</el-col>
            <el-col class="form-border font-small" :span="18">{{formatDate(orderReturnApply.handleTime)}}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">处理备注</el-col>
            <el-col class="form-border font-small" :span="18">{{orderReturnApply.handleNote}}</el-col>
          </el-row>
        </div>
        <div class="form-container-border" v-show="orderReturnApply.status===2">
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">收货人员</el-col>
            <el-col class="form-border font-small" :span="18">{{orderReturnApply.receiveMan}}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6" >收货时间</el-col>
            <el-col class="form-border font-small" :span="18">{{formatDate(orderReturnApply.receiveTime)}}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">收货备注</el-col>
            <el-col class="form-border font-small" :span="18">{{orderReturnApply.receiveNote}}</el-col>
          </el-row>
        </div>
        <div class="form-container-border" v-show="orderReturnApply.status===0">
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">处理备注</el-col>
            <el-col class="form-border font-small" :span="18">
              <el-input  size="small" v-model="updateStatusParam.handleNote" style="width:200px;margin-left: 10px"></el-input>
            </el-col>
          </el-row>
        </div>
        <div class="form-container-border" v-show="orderReturnApply.status===1">
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">收货备注</el-col>
            <el-col class="form-border font-small" :span="18">
              <el-input  size="small" v-model="updateStatusParam.receiveNote" style="width:200px;margin-left: 10px"></el-input>
            </el-col>
          </el-row>
        </div>
        <div style="margin-top:15px;text-align: center" v-show="orderReturnApply.status===0">
          <el-button type="primary" size="small" @click="handleUpdateStatus(1)">确认退货</el-button>
          <el-button type="danger" size="small" @click="handleUpdateStatus(3)">拒绝退货</el-button>
        </div>
        <div style="margin-top:15px;text-align: center" v-show="orderReturnApply.status===1">
          <el-button type="primary" size="small" @click="handleUpdateStatus(2)">确认收货</el-button>
        </div>
      </el-card>
    </div>

  </div>
</template>

<style scoped lang="scss">
.apply-detail {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .apply-card {
    width: 70%;

    .font-title {
      font-size: 20px;
      font-weight: bold;
    }
    .total-title {
      color: #F56C6C;
      float: right;
      font-size: 20px;
      font-weight: bold;
      margin: 20px;
    }
    .el-table {
      margin-top: 20px;
    }
    .form-container-border {
      border-left: 1px solid #DCDFE6;
      border-top: 1px solid #DCDFE6;
      margin-top: 15px;

      .form-border {
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
      }
      .form-left-bg {
        background: #F2F6FC;
      }
      //正文
      .font-small {
        font-size: 14px;
        color: #606266;
      }
    }


  }
}
</style>